package com.xgf.demo.service.impl;

import java.util.List;

import com.sun.org.apache.xpath.internal.operations.Bool;
import com.xgf.demo.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xgf.demo.entity.User;
import com.xgf.demo.repository.UserRespository;
import com.xgf.demo.result.ResultBean;
import com.xgf.demo.service.UserService;

import javax.transaction.Transactional;

import static com.xgf.demo.util.CheckUtil.check;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRespository userRespository;

    @Override
    public List<User> findAll() {
        List<User> userList = userRespository.findAll();
        userList.stream().forEach(user -> {
            User userCreateUser = user.getCreateUser();
            if (userCreateUser != null) {
                user.setOutCreateUser(userRespository.findOneById(userCreateUser.getId()));
            }
        });
        return userList;
    }

    @Override
    public User findById(Long id) {
        check(id > 0L, "id 参数不对", id);
        return userRespository.findOne(id);
    }

    @Override
    public Long save(User user) {
        /**
         * 单纯为了创建用户，不能设置token数据
         */
        user.setTokenTime(null);
        user.setToken(null);
        User save = userRespository.save(user);
        return save.getId();
    }

    @Override
    public User updateById(User user) {
        return userRespository.save(user);
    }

    @Override
    @Transactional
    public Boolean deleteById(Long id) {
        userRespository.deleteById(id, UserUtil.getInstance().getUserId());
        return true;
    }

}
